<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button class="btn save" @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >保存</el-button
        >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item
          name="1"
          v-if="!contactAddShow"
          class="transform-down"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title"
              >{{
                pageType !== "detail" && pageType !== "check "
                  ? pageType === "add"
                    ? "新增"
                    : "编辑"
                  : ""
              }}请购信息</span
            >
          </template>
          <div class="request-info">
            <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="100px"
              v-enterToNext
              :disabled="pageType === 'detail' && pageType === 'check'"
            >
              <el-row>
                <el-col :span="6">
                  <el-form-item label="到票编号：">
                    <el-input
                      disabled
                      v-model="requestForm.purchaseApplyCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="关联合同：">
                    <el-input
                      disabled
                      v-model="requestForm.purchaseContractCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="到票日期：" prop="arrivalInvoiceDate">
                    <el-date-picker
                      v-model="requestForm.arrivalInvoiceDate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办人：" prop="userId">
                    <el-select
                    filterable
                      v-model="requestForm.userId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUserChange"
                    >
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :label="dict.nickName"
                        :value="dict.userId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办部门：">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="开票方：" prop="supplierId">
                    <el-select
                      v-model="requestForm.supplierId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                    >
                      <el-option
                        v-for="dict in suppliereList"
                        :key="dict.supplierId"
                        :label="
                          dict.supplierCode + ' ' + dict.supplierAbbreviation
                        "
                        :value="dict.supplierId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- 添加物料 -->
        <el-collapse-item
          name="2"
          style="position: relative"
          v-if="contactAddShow"
          class="transform-up"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">添加物料</span>
          </template>
          <div class="request-info">
            <el-form
              :model="contactForm"
              ref="contactFormRef"
              :rules="queryContactRules"
              label-width="100px"
              v-enterToNext
            >
              <el-row :gutter="0">
                <el-col :span="6">
                  <el-form-item label="发票类型：" prop="invoiceType">
                    <el-select
                      v-model="contactForm.invoiceType"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleTypeChange"
                    >
                      <el-option
                        v-for="dict in typeList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="发票号：" prop="invoiceCode">
                    <el-input
                      v-model="contactForm.invoiceCode"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="到票金额：" prop="invoiceAmount">
                    <el-input
                      type="Number"
                      v-model="contactForm.invoiceAmount"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    label="关联入库单："
                    prop="purchaseConWarehouseInfoRespVos"
                    label-width="130"
                  >
                    <el-select
                      multiple
                      v-model="contactForm.purchaseConWarehouseInfoRespVos"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUnitChange"
                    >
                      <!-- v-for="dict in unitList" -->
                      <el-option
                        v-for="dict in unitList"
                        :key="dict.warehouseApplyId"
                        :label="
                          dict.warehousingApplyCode +
                          ' ' +
                          dict.applicantDate +
                          ' ' +
                          dict.warehousingQuantity
                        "
                        :value="dict"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="备注：">
                    <el-input
                    maxlength="2000"
                      v-model="contactForm.remarks"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="到票附件：" prop="suppFileInfoVos">
                    <Upload
                      :fileList="contactForm.suppFileInfoVos"
                      :isFull="true"
                      :isCanDelete="true"
                      :showButton="true"
                      accept=".doc,.docx,.pdf"
                      @success="(result) => uploadSuccess(result)"
                      @deleteFile="(result) => uploadRemove(result)"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- 联系人列表 -->
        <el-collapse-item
          name="3"
          style="position: relative"
          :class="!contactAddShow ? 'transform-down' : ''"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title">物料列表</span>
            <div
              v-if="
                pageType !== 'detail' && pageType !== 'check' && !contactAddShow
              "
              class="search-button button-position"
            >
              <el-button class="btn add" @click.stop="handleContactOperate"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >添加</el-button
              >
            </div>
            <div
              class="search-button button-position"
              v-else
              v-if="pageType !== 'detail' && pageType !== 'check'"
            >
              <el-button
                class="btn add"
                @click.stop="handleContactAdd(contactFormRef)"
                ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                >添加</el-button
              >
              <el-button class="btn direction" @click.stop="handleRequestBack"
                ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
                >关闭</el-button
              >
            </div>
          </template>
          <div class="contact-info">
            <!-- 表格数据 -->
            <el-table
              :data="requestForm.purchaseConInvoiceInfoRespVos"
              border
              :height="
                pageType === 'detail' || pageType === 'check'
                  ? '100%'
                  : contactAddShow
                  ? '320px'
                  : '280px'
              "
              :header-cell-style="{ 'text-align': 'center' }"
              show-summary
              sum-text="合计"
              :summary-method="getSummaries"
            >
              <!-- 操作模式 -->
              <el-table-column
                label="操作"
                align="center"
                :show-overflow-tooltip="true"
                width="100px"
                v-if="pageType !== 'detail' && pageType !== 'check'"
              >
                <template #default="{ row, $index }">
                  <div class="table-operate">
                    <img
                      src="@/assets/icons/images/edit.png"
                      class="table-icon"
                      title="编辑"
                      @click="handleOperate('edit', row, $index)"
                    />
                    <img
                      src="@/assets/icons/images/delete.png"
                      class="table-icon"
                      title="删除"
                      @click="handleOperate('delete', row, $index)"
                    />
                  </div> </template
              ></el-table-column>
              <el-table-column
                label="发票类型"
                prop="invoiceTypeName"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="发票号"
                prop="invoiceCode"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="到票金额（元）"
                prop="invoiceAmount"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="关联入库单"
                prop="purchaseConWarehouseInfoRespVos"
                :show-overflow-tooltip="true"
                min-width="160"
              />
              <el-table-column
                label="到票附件"
                prop="suppFileInfoVos"
                :show-overflow-tooltip="true"
                min-width="160"
              >
                <template #default="{ row, $index }">
                  <span v-for="(item, index) in row.suppFileInfoVos">
                    <span>{{ item.name }}</span>
                    <span v-if="index !== row.suppFileInfoVos.length - 1"
                      >，</span
                    >
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="remarks"
                :show-overflow-tooltip="true"
                min-width="160"
              />
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import { checkRequestApi } from "@/api/purchase/request";
import {
  addTicketApi,
  getStoreListApi,
  getTicketDetailApi,
  editTicketApi,
} from "@/api/purchase/contractSeal";
import {
  getProvinceApi,
  getUserListApi,
  getDeptListApi,
  addCustomerApi,
  editCustomerApi,
  getCustomerDetailApi,
} from "@/api/information/customer";
import { getProjectListApi } from "@/api/sales/project";
import {
  addRequestApi,
  editRequestApi,
  getRequestDetailApi,
  getRequestTableApi,
} from "@/api/purchase/request";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestAddShow",
  // 更新客户新增组件显隐
  "update:requestAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  // 合同用印id
  contractId: {
    type: Number,
    default: null,
  },
  // 合同用印编号
  contractCode: {
    type: Number,
    default: null,
  },
});

// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 采购类型列表
const typeList = ref([]);
// 单位列表
const unitList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 项目列表
const projectList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  arrivalInvoiceDate: "", // 	到票日期
  purchaseConInvoiceInfoRespVos: [], // 	到票明细对象
  purchaseContractId: null, // 关联合同id
  purchaseContractCode: null, // 关联合同编号
  remarks: "", // 备注
  supplierId: null, // 开票方
  totalMoney: null, // 到票总金额
  userId: null, // 经办人
  deptName: null, // 部门
};
// 联系人表单数据模板
const contactFormTemplate = {
  contractRelationInvoiceId: null, // 	所属关联发票id
  invoiceAmount: null, // 发票金额
  invoiceCode: "", // 实际发票号
  invoiceType: null, // 发票类型
  invoiceTypeName: "", // 发票类型中文
  remarks: "", // 	备注
  suppFileInfoVos: [], // 合同附件
  purchaseConWarehouseInfoRespVos: [], // 关联入库单
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    arrivalInvoiceDate: [
      { required: true, message: "请选择到票日期", trigger: "change" },
    ],
    userId: [{ required: true, message: "请选择经办人", trigger: "change" }],
    supplierId: [{ required: true, message: "请输入开票方", trigger: "blur" }],
  },
  // 联系人表单校验规则
  queryContactRules: {
    invoiceType: [
      { required: true, message: "请选择发票类型", trigger: "change" },
    ],

    invoiceCode: [{ required: true, message: "请输入发票号", trigger: "blur" }],
    invoiceAmount: [
      { required: true, message: "请输入到票金额", trigger: "blur" },
    ],
    suppFileInfoVos: [
      { required: true, message: "请上传到票附件", trigger: "change" },
    ],
  },
  // 角色列表
  contactTypeList: [],
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
} = toRefs(data);

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res;
          if (!requestForm.value.contractRelationInvoiceId) {
            // 新增客户
            res = await addTicketApi(requestForm.value);
          } else {
            // 编辑客户
            res = await editTicketApi(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:requestAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  selectionMaterialShow.value = true;
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    contactForm.value.materialCode = value.materialCode;
    contactForm.value.materialName = value.materialName;
    contactForm.value.factoryCode = value.factoryCode;
    contactForm.value.technologyParameter = value.technologyParameter;
    contactForm.value.materialUnit = value.materialUnit;
    contactForm.value.materialUnitName = value.materialUnitName;
    contactForm.value.supplierName = value.distributorName;
    contactForm.value.supplierId = value.supplierId;
    contactForm.value.manufacturerId = value.manufacturerId;
    contactForm.value.manufactureName = value.manufactureName;
  } else {
    ElMessage.info("请选择物料");
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value) => {};

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const obj = {
        checkStatus: type,
        purchaseApplyId: requestForm.value.purchaseApplyId,
      };
      const res = await checkRequestApi(obj);
      if (res.code === 200) {
        emit("update:requestAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleType = (value) => {
  if (value == 2 || value == 3) {
    requestForm.value.projectId = null;
  }
  if (value == 0) {
    requestForm.value.budgetAmount = null;
  }
  requestForm.value.projectStatus = null;
  requestForm.value.projectStatusName = "";
  requestForm.value.cloudServer = null;
  requestForm.value.workOrderId = null;
};

/**
 * @description: 处理项目选择
 * @param {Number} value 选择值
 */
const handleProjectChange = (value) => {
  if (value) {
    const selectedProject = projectList.value.find(
      (item) => item.projectId === value
    );
    if (selectedProject) {
      requestForm.value.projectStatus = selectedProject.projectStatus;
      requestForm.value.projectStatusName = selectedProject.projectStatusName;
    }
  } else {
    requestForm.value.projectStatus = null;
    requestForm.value.projectStatusName = "";
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.warehouseApplyName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleTypeChange = (value) => {
  contactForm.value.invoiceTypeName =
    typeList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = (value) => {
  contactForm.value.allPrice =
    (contactForm.value.purchasePrice * contactForm.value.purchaseNumber).toFixed(2);
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        requestForm.value.purchaseConInvoiceInfoRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        requestForm.value.purchaseConInvoiceInfoRespVos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      nextTick(() => {
        refInput.value.focus();
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  contactForm.value.suppFileInfoVos.push({ ...response, businessType: 10 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  contactForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 联系人返回
 */
const handleRequestBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (column.property === "invoiceAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  // if (props.pageType === "add" || props.pageType === "edit") {
  //   sums[8] = sums[6] * sums[7];
  //   sums[7] = "";
  // } else {
  //   sums[7] = sums[5] * sums[6];
  //   sums[6] = "";
  // }

  return sums;
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = {
      ...JSON.parse(JSON.stringify(row)),
      suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
        ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
        : [],
    };
    contactForm.value.allPrice =
      (contactForm.value.purchasePrice * contactForm.value.purchaseNumber).toFixed(2);
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    requestForm.value.purchaseConInvoiceInfoRespVos.splice(tabIndex, 1);
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getTicketDetailApi(id);
    if (res) {
      requestForm.value = res;
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 类型
  await getDictsApi("erp_invoice_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });

  // 入库列表
  await getStoreListApi().then((res) => {
    if (res) {
      unitList.value = res;
    }
  });

  // 供应商列表
  await getSupplierListApi().then((res) => {
    if (res.code === 200) {
      res.rows.forEach((item) => {
        item.value = item.supplierName;
      });
      suppliereList.value = res.rows;
    }
  });

  // 项目列表
  await getProjectListApi({}, {}).then((res) => {
    if (res.code === 200) {
      projectList.value = res.rows;
    }
  });

  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}

onMounted(() => {
  nextTick(() => {
    requestForm.value.purchaseContractId = props.contractId;
    requestForm.value.purchaseContractCode = props.contractCode;
  });
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
